package org.groupg.practice;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.function.Consumer;

public class MainDataSource {
    private static final String driver = "org.postgresql.Driver";
    private static final String url = "jdbc:postgresql://localhost:5432/demodb";
    private static final String user = "demouser";
    private static final String password = "demouser";

    private static final BasicDataSource ds;

    static {
        ds = new BasicDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(user);
        ds.setPassword(password);
        ds.setInitialSize(20);
    }

    private static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    public static void close() throws SQLException {
        ds.close();
    }
    public static void execUpdate(Consumer<Statement> statementConsumer) throws SQLException {
        Connection connection = getConnection();
        connection.setAutoCommit(true);
        Statement statement = connection.createStatement();
        statementConsumer.accept(statement);
        statement.close();
        connection.close();
    }

    public static void execQuery(Consumer<Statement> statementConsumer) throws SQLException {
        Connection connection = getConnection();
        connection.setReadOnly(true);
        Statement statement = connection.createStatement();
        statementConsumer.accept(statement);
        statement.close();
        connection.close();
    }
}
